package net.tyw.web.ctrl;

import com.alibaba.fastjson.JSON;
import net.tyw.common.JSONResult;
import net.tyw.common.exception.ServiceException;
import net.tyw.common.paginator.domain.PageBounds;
import net.tyw.common.paginator.domain.PageResult;
import net.tyw.common.utils.DateUtil;
import net.tyw.common.utils.ValidateUtil;
import net.tyw.core.auth.Oauth;
import net.tyw.core.enums.oauth.Gender;
import net.tyw.core.enums.oauth.UserLoginAccountType;
import net.tyw.core.enums.oauth.UserState;
import net.tyw.core.model.oauth.RoleInfo;
import net.tyw.core.model.oauth.UserInfo;
import net.tyw.core.model.oauth.UserLoginAccount;
import net.tyw.core.service.oauth.UserInfoService;
import net.tyw.core.vo.oauth.UserInfoVo;
import net.tyw.web.params.ListUserParam;
import net.tyw.web.params.SaveUserParam;
import net.tyw.web.servlet.ServletContext;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserCtrl {

    private final static Logger logger = LoggerFactory.getLogger(UserCtrl.class);


    @Autowired
    private UserInfoService userInfoService;

    @Oauth
    @ResponseBody
    @RequestMapping("/list")
    public JSONResult listUser(@RequestBody ListUserParam param) {
        PageResult<UserInfo> pageResult = this.userInfoService.findPage(new PageBounds(param.getCurrentPage(), param.getLimit()), new UserInfoVo());
        for (UserInfo userInfo : pageResult.getData()) {
            userInfo.setListUserLoginAccount(this.userInfoService.findAllLoginAccount(userInfo.getId()));
        }
        return JSONResult.instance().setData(pageResult);
    }

    @Oauth
    @ResponseBody
    @RequestMapping("/save")
    public JSONResult saveUser(@RequestBody SaveUserParam param) {
        logger.debug(JSON.toJSONString(param));

        if (param.getId() == null) {
            if (ValidateUtil.isBlank(param.getEmail()) || !ValidateUtil.isEmail(param.getEmail())) {
                return JSONResult.instance("empty_email", "请输入正确的邮箱");
            }
            UserLoginAccount emailLoginAccount = this.userInfoService.findLoginAccount(param.getEmail(), UserLoginAccountType.email);
            if (emailLoginAccount != null) {
                return JSONResult.instance("email_is_exist", "邮箱" + param.getEmail() + "已经存在");
            }
            if (StringUtils.isBlank(param.getMp()) || !ValidateUtil.isMobile(param.getMp())) {
                return JSONResult.instance("empty_mp", "请输入正确的手机号");
            }

            UserLoginAccount mpLoginAccount = this.userInfoService.findLoginAccount(param.getMp(), UserLoginAccountType.mp);
            if (mpLoginAccount != null) {
                return JSONResult.instance("email_is_exist", "手机号" + param.getMp() + "已经存在");
            }


        }

        if (param.getId() == null || (param.getId() != null && StringUtils.isNotBlank(param.getLoginPassword()))) {
            if (StringUtils.isBlank(param.getLoginPassword())) {
                return JSONResult.instance("empty_login_password").setMessage("请输入登录密码！");
            }
            if (!StringUtils.equals(param.getLoginPassword(), param.getConfirmPassword())) {
                return JSONResult.instance("not_equals_login_password").setMessage("确认密码与登录不一致！");
            }
        }

        if (StringUtils.isBlank(param.getNickName())) {
            return JSONResult.instance("empty_nick_name").setMessage("请输入用户昵称！");
        }

        if (param.getGender() == null) {
            param.setGender(Gender.secret);
        }
        if (param.getState() == null) {
            param.setState(UserState.normal);
        }

        UserInfo userInfo = new UserInfo();
        userInfo.setId(param.getId());
        userInfo.setNickName(param.getNickName());
        userInfo.setState(param.getState());
        userInfo.setGender(param.getGender());
        userInfo.setRegisterTime(DateUtil.current());
        userInfo.setRegisterIp(ServletContext.getRemoteIp());

        try {
            if (param.getId() == null) {
                this.userInfoService.register(userInfo, param.getEmail(), param.getMp(), param.getLoginPassword(), param.getRoles());
            } else {
                this.userInfoService.updateUserInfo(userInfo, param.getLoginPassword(), param.getRoles());
            }
            return JSONResult.instance().setMessage("保存用户成功");
        } catch (ServiceException e) {
            logger.error("", e);
            return JSONResult.instance("system_error").setMessage("系统忙，请稍后再试");
        }

    }

    @Oauth
    @ResponseBody
    @RequestMapping("/disabled")
    public JSONResult disabled(@RequestBody String stringUids) {
        try {
            logger.debug(JSON.toJSONString(stringUids));
            List<Long> listUids = JSON.parseArray(stringUids, Long.class);
            if (!listUids.isEmpty()) {
                for (Long uid : listUids) {
                    UserInfo userInfo = new UserInfo();
                    userInfo.setId(uid);
                    userInfo.setState(UserState.disable);
                    this.userInfoService.updateUserInfo(userInfo, "", null);
                }
            }
            return JSONResult.instance().setMessage("禁用用户成功");
        } catch (ServiceException e) {
            logger.error("", e);
            return JSONResult.instance("system_error").setMessage("系统忙，请稍后再试");
        }
    }

    @Oauth
    @ResponseBody
    @RequestMapping("/enabled")
    public JSONResult enabled(@RequestBody String stringUids) {
        try {
            logger.debug(JSON.toJSONString(stringUids));
            List<Long> listUids = JSON.parseArray(stringUids, Long.class);
            if (!listUids.isEmpty()) {
                for (Long uid : listUids) {
                    UserInfo userInfo = new UserInfo();
                    userInfo.setId(uid);
                    userInfo.setState(UserState.normal);
                    this.userInfoService.updateUserInfo(userInfo, "", null);
                }
            }
            return JSONResult.instance().setMessage("禁用用户成功");
        } catch (ServiceException e) {
            logger.error("", e);
            return JSONResult.instance("system_error").setMessage("系统忙，请稍后再试");
        }
    }

    @Oauth
    @ResponseBody
    @RequestMapping("/findById")
    public JSONResult findById(@RequestBody Map<String, Long> param) {
        logger.debug(JSON.toJSONString(param.get("uid")));
        UserInfo userInfo = this.userInfoService.findUserInfoById(param.get("uid"));
        userInfo.setListUserLoginAccount(this.userInfoService.findAllLoginAccount(userInfo.getId()));
        List<RoleInfo> listRoles = this.userInfoService.findRoleByUser(param.get("uid"));
        List<Long> hasRoles = new ArrayList<>();
        if (listRoles != null && listRoles.size() > 0) {
            for (RoleInfo roleInfo : listRoles) {
                hasRoles.add(roleInfo.getId());
            }
        }
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("hasRoles", hasRoles);
        dataMap.put("userInfo", userInfo);
        return JSONResult.instance().setData(dataMap);

    }
}
